

import { seoEventEmit, seoEventTypeEnum } from '@/core/seoEvent';
import { addMsg } from '@database/services/chat-management-service';
import { ChatMessage } from '@/database/entity/chat';
import { ServiceConfig } from '@/core/servicePath';
import {getAppConfigItem} from '@/assets/ts/app-config';

// 定义事件类型
enum WebSocketMessageType {
  CHAT = 'chat',
  NOTICE = 'notice',
  SERVICE = 'service',
  SPARK = 'spark',
}

interface WebSocketData {
  user: string;
  type: string;
  content: string;
}

class WebSocketService {
  private url: string;
  private contentTemp: string | null = "";
  public ws: WebSocket | null = null;

  constructor(url: string) {
    this.url = url;
  }

  // 连接
  connect() {
    this.ws = new WebSocket(this.url);
    this.ws.onopen = () => {
      console.log('WebSocket开始连接');
    };

    this.ws.onmessage = (event: MessageEvent) => {
      const eventData = JSON.parse(event.data);
      const messageType: WebSocketMessageType = WebSocketMessageType.CHAT;
      if (eventData.type.toString() == messageType) {
        seoEventEmit(seoEventTypeEnum.WEB_SOCKET_MESSAGE, event.data)
      }
     
      const chatMessage: ChatMessage = { user: eventData.userId, content: eventData.content, type: eventData.type };
      if (eventData.type.toString() == WebSocketMessageType.CHAT) {
        chatMessage.type = WebSocketMessageType.CHAT
        addMsg(chatMessage)
      }else if (eventData.type.toString() == WebSocketMessageType.SPARK) {
        seoEventEmit(seoEventTypeEnum.SPARK_MESSAGE, event.data)
        if(chatMessage.content == WebSocketMessageType.SPARK){
          chatMessage.content = this.contentTemp!;
          chatMessage.user = 'spark';
          chatMessage.type = WebSocketMessageType.SPARK
          addMsg(chatMessage)
        }else{
          this.contentTemp += chatMessage.content;
        }
      }
    
    };

    this.ws.onclose = () => {
      console.log('WebSocket 断开连接');
    };

    this.ws.onerror = (error: Event) => {
      console.error('WebSocket 错误', error);
    };
  }

  // 发送消息
  sendMessage(message: string) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      let mag = { "content": message }
      this.ws.send(JSON.stringify(mag));
    } else {
      console.error('WebSocket is not open');
    }
  }

  close() {
    if (this.ws) {
      this.ws.close();
    }
  }
}


let webSocket: WebSocketService | null = null;
// 守护线程
let guardian = setInterval(function(){
    const loginName = getAppConfigItem('loginName');
    if(loginName !='default' && webSocket?.ws?.readyState != WebSocket.OPEN){
      console.info('重新连接' + ServiceConfig.wsUrl + loginName);
      Connect(ServiceConfig.wsUrl + loginName);
      console.info('重新连接成功');
    }
}, 3000);

function Connect(url: string) {
  if (webSocket) {
    return;
  }
  webSocket = new WebSocketService(url)
  webSocket.connect()
  seoEventEmit(seoEventTypeEnum.WEB_SOCKET_CONNECT,"")
}

function Send(message: string) {
  webSocket?.sendMessage(message)
}


function Close() {
  webSocket?.close()
}

export { WebSocketData, Connect, Send , Close}